<template>
  <base-modal
    class="service-dialog-container"
    :title="$t('common.fields.email.displayName')"
    :show.sync="visible"
    width="850px"
  >
    <div class="base-modal-content wrapper">
      <el-form label-position="top" ref="form">
        <el-form-item :label="$t('event.detail.components.dialog.text5')">
          <el-radio-group v-model="shareType">
            <el-radio :label="1">{{$t('event.detail.components.dialog.text1')}}</el-radio>
            <el-radio :label="2">{{$t('event.detail.components.dialog.text2')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('common.base.addressee')">
          <el-input v-if="shareType==1" v-model="selectedAddressee_external" :placeholder="$t('event.detail.components.dialog.text6')">
            <i slot="suffix" class="iconfont icon-add2" @click="add_email('addressee')"></i>
          </el-input>
          <EmailSelectItem v-if="shareType==2" :selected-list="selectedAddressee" :placeholder="$t('common.base.pleaseSelect')" :show-max-num="8" @updateTag="updateSelectedAddressee"></EmailSelectItem>
        </el-form-item>
        <el-form-item :label="$t('common.paas.view.designer.workFlow.carbonCopy')">
          <el-input v-if="shareType==1" v-model="selectedCopy_external" :placeholder="$t('event.detail.components.dialog.text7')">
            <i slot="suffix" class="iconfont icon-add2" @click="add_email('copy')"></i>
          </el-input>
          <EmailSelectItem v-if="shareType==2" :selected-list="selectedCopy" :placeholder="$t('common.base.pleaseSelect')" :show-max-num="8" @updateTag="updateSelectedCopy"></EmailSelectItem>
        </el-form-item>
        <el-form-item :label="$t('event.detail.components.dialog.text8')">
          <el-input v-model="params.title" />
        </el-form-item>
        <el-form-item class="create-item">
          <div class="file">
            <div class="base-comment-attachment base-file__preview file-item" v-if="params.form.attachments && params.form.attachments.length > 0">
              <base-file-item v-for="file in params.form.attachments" :source="params.form.attachments" :key="file.id" :file="file" @delete="deleteFile" size="small"></base-file-item>
            </div>
            <button type="button" class="base-comment-tool file-button" @click="chooseFile">
              <i class="iconfont icon-attachment"></i> {{$t('event.detail.components.dialog.text3')}}
            </button> 
            <input type="file" ref="input" @change="handleChange" multiple>
            <div class="base-comment-cover loading" v-if="!allowOperate">
              <base-spin :text="$t('common.base.waiting')"></base-spin>
            </div>
          </div> 
        </el-form-item>
      </el-form>
      <!-- 富文本编辑器 -->
      <base-editor v-if="editShow" class="editor-wrapper" v-model="params.article" @input="getInput" ref="editor"></base-editor>
    </div>
    <div slot="footer" class="dialog-footer">
      <span class="sjr" v-if="emailInfo.email">{{$t('event.detail.components.dialog.text4')}}：{{`<${emailInfo.emailAlias}>${emailInfo.email}`}}</span>
      <div>
        <el-button @click="cancelWindow">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="submit" :loading="btnPending">{{$t('common.base.send')}}</el-button>
      </div>
    </div>
  </base-modal>
</template>

<script>
import EmailSelectItem from './components/EmailSelectItem.vue';
import Uploader from '@src/util/uploader';
import { getRootWindowInitData } from '@src/util/window'
import * as EventApi from '@src/api/EventApi.js';

import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'

export default {
  name: 'email-sharing-dialog',
  components:{
    EmailSelectItem
  },
  props:{
    workEvent:{
      type:Object,
      default:()=>({})
    }
  },
  data () {
    return {
      visible:false,
      pending:false,
      btnPending:false,
      params: {
        title: '', // 主题
        rule: true,
        sendPeople:'',
        article: '', // 文章内容
        form: {
          content: '',
          attachments: [],
          showInOwn: 0
        }, // 附件
      },
      selectedAddressee: [], // 选择的收件人
      selectedCopy: [], // 选择的抄送人
      loginUser: {}, // 当前登录的用户
      emailInfo:{},
      editShow:true,
      article_inside:'', // 内部分享内容
      article_external:'', // 外部部分享内容
      selectedAddressee_external:'', // 外部分享收件人
      selectedCopy_external:'', // 外部分享抄送人
      shareType:1, // 分享方式 1：外部分享 2:内部分享
      domainId:'',
    }
  },
  computed:{
    // 加载显示
    allowOperate(){
      return !this.pending
    },
    originUrl(){
      return window.location.origin
    }
  },
  watch:{
    shareType(){
      this.setArticle()
    }
  },
  mounted(){
    this.init()
  },
  methods: {
    openDialog(){
      if (!this.visible) {
        return this.visible = true
      }
    },
    async submit(){
      try{
        this.btnPending = true
        let attachmentList = this.params.form.attachments.map((v)=>{
          return {
            id:v.id,
            url:v.url,
            name:v.filename,
            fileSize:v.fileSize,
            size:v.size
          }
        })
        const params = {
          tenantId:this.loginUser.tenantId,
          eventNo:this.workEvent.eventNo,
          theme:this.params.title,
          attachmentList,
          emailContent:this.params.article,
          userId:this.loginUser.userId,
          displayName:this.loginUser.loginName,
          eventId:this.workEvent.id
        }
        if(this.shareType == 1){
          if(!this.selectedAddressee_external) return this.$message.error(this.$t('event.detail.components.dialog.text9'))
          let receiveUserEmailList = await this.getEmailList(this.selectedAddressee_external, 1)
          let ccUserEmailList = await this.getEmailList(this.selectedCopy_external, 2)
          params.receiveUserEmailList = receiveUserEmailList
          params.ccUserEmailList = ccUserEmailList
          params.internally = false
        }else if(this.shareType == 2){
          if(this.selectedAddressee.length <= 0) return this.$message.error(this.$t('event.detail.components.dialog.text10'))
          let receiveUserList = this.selectedAddressee.map(v=>v.userId)
          let ccUserList = this.selectedCopy.map(v=>v.userId)
          params.receiveUserList = receiveUserList
          params.ccUserList = ccUserList
        }
        const {status, message} = await EventApi.emailShare(params)
        if(status == 0){
          this.$message.success(message)
          this.cancelWindow()
        }else{
          this.$message.error(message)
        }
      }catch(err){
        console.error(err)
        this.$message.error(err || this.$t('event.detail.components.dialog.text11'))
      }finally{
        this.btnPending = false
      }
    },
    cancelWindow(){
      this.visible = false
    },
    // 获取带格式的文章内容
    getInput (html) {
      if(this.shareType == 1){
        this.article_external = html
      }else if(this.shareType == 2){
        this.article_inside = html
      }
      return html;
    },
    // 更新选择的收件人
    updateSelectedAddressee(val){
      this.selectedAddressee = val
    },

    // 更新选择的抄送送人
    updateSelectedCopy(val){
      this.selectedCopy = val
    },
    // 选择文件
    handleChange(event){
      const files = event.target.files;
      if(!files || !files.length) return;
      let form = this.params.form;
      let size = files[0].size / 1024 / 1024
      if(size > 50){
        return this.$platform.alert(this.$t('event.detail.components.dialog.text12'))
      }
      this.pending = true;
      Uploader.batchUploadWithParse({files, action: '/files/upload/wiki', source: 'event'}).then(result => {
        let {success, error} = result;
        if(error.length > 0){
          let message = error.map(item => item.message).join('\n');
          this.$platform.alert(message)
        }
        if(success.length > 0){
          form.attachments = form.attachments.concat(success);
        }
      })
        .catch(err => console.error(err))
        .then(() => this.pending = false)
    },
    // 删除文件
    deleteFile(file) {
      let index = this.params.form.attachments.indexOf(file);
      if(index >= 0) {
        this.params.form.attachments.splice(index, 1);
      }
    },
    // 触发inputclick事件选择文件
    chooseFile () {
      if(this.pending) return this.$platform.alert(this.$t('common.base.uploadModal.tips1'));
      this.$refs.input.value = null;
      this.$refs.input.click();
    },
    // 查询邮箱配置详情
    async getTenantEmail(){
      const {code, data} = await EventApi.getEmailConfig()
      if(code == 0){
        this.emailInfo = data || {}
      }
    },
    async reset(){
      this.params = {
        title: '', // 主题
        rule: true,
        sendPeople:'',
        article: '', // 文章内容
        form: {
          content: '',
          attachments: [],
          showInOwn: 0
        }, // 附件
      }
      this.selectedAddressee = []
      this.selectedCopy = []
      this.selectedAddressee_external = ''
      this.selectedCopy_external = ''
      this.params.title = this.$t('event.detail.components.dialog.text13', {data1: this.workEvent.cusName, data2: this.workEvent.eventNo})
      this.setArticle()
    },
    async getShortenUrl(shareType){
      let url = ''
      try{
        let {id, tenantId, templateId, eventNo} = this.workEvent
        if(shareType == 2){
          url = `${this.originUrl}?shareUrl=${encodeURIComponent(`${this.originUrl}/shb/home/event/view?id=${id}&eventNo=${eventNo}`)}`
        }else if(shareType == 1){
          url = `${this.originUrl}/p/${this.domainId}#/event/view?id=${id}&model=event&tenantId=${tenantId}&templateId=${templateId}&shareFrom=eventView`
        }
        const {status, data} = await EventApi.getShortenUrl({url})
        if(status == 0){
          return Promise.resolve(data)
        }
        // 转链失败返回原链接
        return Promise.resolve(url)
        
      }catch(err){
        return Promise.resolve(url)
      }
      
    },
    toggleEditShow(){
      this.editShow = false
      this.$nextTick(()=>{
        this.editShow = true
      })
    },
    async setArticle(){
      this.params.article = this.shareType == 1 ? this.article_external : this.article_inside
      this.toggleEditShow()
    },
    async init(){
      try{
        this.loginUser = getRootWindowInitData().user || {}
        this.getTenantEmail()
        await this.getDomainId()
        let url_external = await this.getShortenUrl(1)
        let url_inside = await this.getShortenUrl(2)
        this.article_external = this.$t('event.detail.components.dialog.text14', {data1: this.workEvent.cusName, data2: url_external, data3: url_external})
        this.article_inside = this.$t('event.detail.components.dialog.text14', {data1: this.workEvent.cusName, data2: url_inside, data3: url_inside})
        this.setArticle()
        this.params.title = this.$t('event.detail.components.dialog.text13', {data1: this.workEvent.cusName, data2: this.workEvent.eventNo})
      }catch(err){
        console.log(err)
      }
    },
    getEmailList(str, type){
      let text = type == 1 ? this.$t('common.base.addressee') : this.$t('common.paas.view.designer.workFlow.carbonCopy')
      // 抄送人可为空
      if(!str && type == 2) return []
      try{
        let list = str.split(',')
        let reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
        let isError = list.find( v=>!reg.test(v))
        if(isError) return Promise.reject(this.$t('event.detail.components.dialog.text15', {data1: text}))
        return list
      }catch(err){
        return Promise.reject(this.$t('event.detail.components.dialog.text15', {data1: text}))
      }
    },
    async getDomainId(){
      const {status, data} = await EventApi.getDomainId({
        tenantId:this.loginUser.tenantId
      })
      if(status == 0){
        this.domainId = data
      }
    },
    add_email(type) {
      
      let options = {
        title: this.$t('common.placeholder.selectMember'),
        unique: false,
        max: -1,
        isNeedEmail: true,
        mode: BaseSelectUserModeEnum.Filter
      };
      
      this.$fast.select.multi.user(options).then(result => {
        if(result.status == 0){
          let str = `${result.data.users.map(v=>v.email).join(',') },`
          if(type == 'addressee'){
            this.selectedAddressee_external += str
          }else if(type == 'copy'){
            this.selectedCopy_external += str
          }
        }
      })
        .catch(err => console.error(err))
    }

  }
}
</script>

<style scoped lang='scss'>
  .service-dialog-container{
    ::v-deep .base-modal-body {
      padding: 10px 15px 0;
    }
    .create-item {
    position: relative;
    width: 100%;
    margin: 0;

    .el-radio {
      line-height: 30px;

      .el-radio__label {
        font-size: 13px;
      }
    }

    .icon-permission {
      position: relative;
      top: 1px;

      font-size: 14px;
      margin-left: 4px;
    }

    .search-tag {
      margin-left: 4px;
      border: none;
      background: #E8EFF0;
      color: #606266;
      line-height: 24px;
    }

    .input-new-tag {
      display: inline-block;
      width: 80px;
    }

    .icon-add-tags-btn {
      display: inline-block;
      position: relative;
      top: 2px;
      width: 20px;
      height: 20px;
      line-height: 20px;

      margin-left: 5px;

      cursor: pointer;
      .icon-addTags {
        font-size: 14px;
        @include fontColor();
      }
    }
    
    input[type='file']{
      display: none !important;
    }

    .file {
      font-size: 0;
      .file-item {
        display: inline-flex;
        flex-wrap: wrap;

        vertical-align: middle;

        .base-file-info-name {
          max-width: 350px;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .file-button {
        vertical-align: middle;
        margin-left: 8px;
      }

      .loading {
        bottom: 10px;

        .base-spin-text {
          padding: 0;
        }
      }
    }

    .range {
      margin-left: 82px;

      .notification-range {
        position: absolute;
        bottom: 0;
        z-index: -20;
        display: inline-block;
        width: calc(100% - 82px);
        border: none;

        .biz-team-select-tags {
          display: none;
        }
      }
    }

    .el-input__inner {
      border-color: #e0e1e2;
    }
    
    
  }
  .editor-wrapper{
    margin-top: 20px;
  }
  .dialog-footer{
    display: flex;
    width: 100%;
    justify-content: space-between;
    .sjr{
      font-size: 14px;
      color: #262626;
    }
  }
  .icon-add2{
      padding-right: 5px;
      cursor: pointer;
    }
  }
</style>